using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Publicuse.Autofac;
using Publicuse.Cache;
using Publicuse.Entity;
using Publicuse.Entity.AttributeUtil.Validate;
using Publicuse.Util;
using Renci.SshNet.Common;
using ServiceStack;
using SqlSugar;
using static FreeSql.Internal.GlobalFilter;

namespace Publicuse.Appication
{
    public class UserApplication
    {
        private static BaesApplication baseApplication;
        private static UserApplication userApplication;

        public static UserApplication GetApplication(ServiceContainer container)
        {
            baseApplication = new BaesApplication(container);
            return userApplication;
        }

        static UserApplication()
        {
            userApplication = new UserApplication();
        }

        /// <summary>
        /// 获取当前登录账号相关信息
        /// </summary>
        /// <returns></returns>
        public async Task<CommonResult> GetUserInfo()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var LoginuId = HttpContextExtendBase.GetLoginuId().GetLongValue();
                var userlist = baseApplication.mySqlSugar.QueryByExpression<User>(
                    o => o.Id == LoginuId && o.status == 1,
                    out string msg
                );
                if (userlist != null && userlist.Count > 0)
                {
                    User user = userlist.FirstNonDefault();
                    user.rName = HttpContextExtendBase.GetLoginrName();
                    user.rId = HttpContextExtendBase.GetLoginRsId();

                    var lasttimeupw = user.lasttimeupw;
                    var resetpwd = user.resetpwd;
                    if (string.IsNullOrEmpty(lasttimeupw))
                    {
                        user.isNeedUpdatePwd = true;
                        user.needUpdatePwdMsg = "，首次登录需要先修改密码,请先修改密码！";
                    }
                    if (string.Compare(resetpwd, "是", true) == 0)
                    {
                        user.isNeedUpdatePwd = true;
                        user.needUpdatePwdMsg = "，您的账号已重置密码,请先修改密码！";
                    }

                    result.count = 1;
                    result.data = user;

                    var token = HttpContextExtendBase.GetTokenStr();
                    UserRouteData userRouteData = LoginCache.GetLoginCache.GetUserRouteData(token);
                    if (userRouteData != null)
                    {
                        result.datab = userRouteData;
                    }
                    var LoginAction = LoginCache.GetLoginCache.GetLoginMenu(token);
                    List<UserMenuAction> userActionLists = new List<UserMenuAction>();
                    if (LoginAction.Count > 0)
                    {
                        LoginAction.ForEach(item =>
                        {
                            userActionLists.Add(
                                new UserMenuAction { menuCode = item.aCode, menuName = item.aName }
                            );
                        });
                        result.datac = userActionLists;
                    }
                }
                else
                {
                    result.msg = "用户不存在或已被禁用";
                }
                return result;
            });
        }

        /// <summary>
        /// 获取当前登录账号模块菜单权限
        /// </summary>
        /// <param name="routetitle"></param>
        /// <param name="routeurl"></param>
        /// <returns></returns>
        public async Task<CommonResult> Gettmpotclam(string routetitle, string routeurl)
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var LoginuId = HttpContextExtendBase.GetLoginuId();
                var LoginAppid = HttpContextExtendBase.GetLoginAppid();
                var LoginCode = HttpContextExtendBase.GetLoginCode();
                string msg = string.Empty;
                UserFunctionMenu functionMenu = new UserFunctionMenu();
                if (string.IsNullOrEmpty(LoginuId))
                {
                    result.msg = "会话超时请重新登录！";
                }
                else
                {
                    List<Menu> list = new List<Menu>();
                    if (
                        string.Compare(LoginAppid, "admin", true) != 0
                        && string.Compare(LoginCode, "ajng", true) != 0
                        && string.Compare(LoginCode, "广州市教育局", true) != 0
                        && string.Compare(LoginCode, "戴奕彬", true) != 0
                    )
                    {
                        var urm = TableAtributeUtil.GetTable<URPermission>();
                        var author = TableAtributeUtil.GetTable<Menu>();
                        var modulename = routeurl.Split('/')[2];
                        var sql =
                            $"select a.aName,a.Id,a.aCode,ahtmlUrl,aapiUrl,aParentId from {author} a left join {urm} b on FIND_IN_SET(a.Id,b.aIds) where b.uId={LoginuId} and a.status<>-9 and b.status<>-9 and a.aType=3 and a.aapiUrl like '%{modulename}%';";
                        list = baseApplication.mySqlSugar.Query<Menu>(sql, out msg);
                        if (string.IsNullOrEmpty(msg) && list != null)
                        {
                            if (list.Count > 0)
                            {
                                var routeurls = routeurl.Replace("index", "api").Split('/');
                                var newrouteurl = routeurls[0] + "/" + routeurls[2] + "/";
                                if (
                                    list.Any(o =>
                                        o.aapiUrl.ToLower() == (newrouteurl + "CheckAdd").ToLower()
                                    )
                                )
                                {
                                    functionMenu.isadd = true;
                                }
                                if (
                                    list.Any(o =>
                                        o.aapiUrl.ToLower()
                                        == (newrouteurl + "CheckDelete").ToLower()
                                    )
                                )
                                {
                                    functionMenu.isdelete = true;
                                }
                                if (
                                    list.Any(o =>
                                        o.aapiUrl.ToLower()
                                        == (newrouteurl + "CheckUpdate").ToLower()
                                    )
                                )
                                {
                                    functionMenu.isupdate = true;
                                }
                                if (
                                    list.Any(o =>
                                        o.aapiUrl.ToLower()
                                        == (newrouteurl + "CheckGetList").ToLower()
                                    )
                                )
                                {
                                    functionMenu.isquery = true;
                                }
                                if (
                                    list.Any(o =>
                                        o.aapiUrl.ToLower()
                                        == (newrouteurl + "CheckImport").ToLower()
                                    )
                                )
                                {
                                    functionMenu.isimport = true;
                                }
                                if (
                                    list.Any(o =>
                                        o.aapiUrl.ToLower()
                                        == (newrouteurl + "CheckExport").ToLower()
                                    )
                                )
                                {
                                    functionMenu.isexport = true;
                                }
                                if (
                                    list.Any(o =>
                                        o.aapiUrl.ToLower() == (newrouteurl + "CheckDown").ToLower()
                                    )
                                )
                                {
                                    functionMenu.isdown = true;
                                }
                                if (
                                    list.Any(o =>
                                        o.aapiUrl.ToLower()
                                        == (newrouteurl + "CheckUpload").ToLower()
                                    )
                                )
                                {
                                    functionMenu.isupload = true;
                                }
                                if (
                                    list.Any(o =>
                                        o.aapiUrl.ToLower()
                                        == (newrouteurl + "CheckAudit").ToLower()
                                    )
                                )
                                {
                                    functionMenu.iscomfirm = true;
                                }
                                if (
                                    list.Any(o =>
                                        o.aapiUrl.ToLower()
                                        == (newrouteurl + "CheckRoleResource").ToLower()
                                    )
                                )
                                {
                                    functionMenu.isroleresource = true;
                                }
                                if (
                                    list.Any(o =>
                                        o.aapiUrl.ToLower()
                                        == (newrouteurl + "CheckCompany").ToLower()
                                    )
                                )
                                {
                                    functionMenu.iscompany = true;
                                }
                                if (
                                    list.Any(o =>
                                        o.aapiUrl.ToLower()
                                        == (newrouteurl + "CheckDepartment").ToLower()
                                    )
                                )
                                {
                                    functionMenu.isdepartment = true;
                                }
                                if (
                                    list.Any(o =>
                                        o.aapiUrl.ToLower()
                                        == (newrouteurl + "CheckSchool").ToLower()
                                    )
                                )
                                {
                                    functionMenu.isschool = true;
                                }
                                if (
                                    list.Any(o =>
                                        o.aapiUrl.ToLower()
                                        == (newrouteurl + "CheckRecyclebin").ToLower()
                                    )
                                )
                                {
                                    functionMenu.isrecyclebin = true;
                                }
                            }
                            else
                            {
                                var LoginrId = HttpContextExtendBase.GetLoginrId();
                                var roleres = TableAtributeUtil.GetTable<RoleResource>();
                                sql = $"select * from {roleres} where rId in({LoginrId});";
                                var rolereslist = baseApplication.mySqlSugar.Query<RoleResource>(
                                    sql,
                                    null,
                                    out msg
                                );
                                if (
                                    string.IsNullOrEmpty(msg)
                                    && rolereslist != null
                                    && rolereslist.Count > 0
                                )
                                {
                                    var aids = string.Join(",", rolereslist.Select(o => o.aIds));
                                    sql =
                                        $"select a.aName,a.Id,a.aCode,ahtmlUrl,aapiUrl,aParentId from {author} a where aapiUrl<>'' and Id in({aids});";
                                    list = baseApplication.mySqlSugar.Query<Menu>(
                                        sql,
                                        null,
                                        out msg
                                    );
                                    if (list.Count > 0)
                                    {
                                        var routeurls = routeurl.Replace("index", "api").Split('/');
                                        var newrouteurl = routeurls[0] + "/" + routeurls[2] + "/";
                                        if (
                                            list.Any(o =>
                                                o.aapiUrl.ToLower()
                                                == (newrouteurl + "CheckAdd").ToLower()
                                            )
                                        )
                                        {
                                            functionMenu.isadd = true;
                                        }
                                        if (
                                            list.Any(o =>
                                                o.aapiUrl.ToLower()
                                                == (newrouteurl + "CheckDelete").ToLower()
                                            )
                                        )
                                        {
                                            functionMenu.isdelete = true;
                                        }
                                        if (
                                            list.Any(o =>
                                                o.aapiUrl.ToLower()
                                                == (newrouteurl + "CheckUpdate").ToLower()
                                            )
                                        )
                                        {
                                            functionMenu.isupdate = true;
                                        }
                                        if (
                                            list.Any(o =>
                                                o.aapiUrl.ToLower()
                                                == (newrouteurl + "CheckGetList").ToLower()
                                            )
                                        )
                                        {
                                            functionMenu.isquery = true;
                                        }
                                        if (
                                            list.Any(o =>
                                                o.aapiUrl.ToLower()
                                                == (newrouteurl + "CheckImport").ToLower()
                                            )
                                        )
                                        {
                                            functionMenu.isimport = true;
                                        }
                                        if (
                                            list.Any(o =>
                                                o.aapiUrl.ToLower()
                                                == (newrouteurl + "CheckExport").ToLower()
                                            )
                                        )
                                        {
                                            functionMenu.isexport = true;
                                        }
                                        if (
                                            list.Any(o =>
                                                o.aapiUrl.ToLower()
                                                == (newrouteurl + "CheckDown").ToLower()
                                            )
                                        )
                                        {
                                            functionMenu.isdown = true;
                                        }
                                        if (
                                            list.Any(o =>
                                                o.aapiUrl.ToLower()
                                                == (newrouteurl + "CheckUpload").ToLower()
                                            )
                                        )
                                        {
                                            functionMenu.isupload = true;
                                        }
                                        if (
                                            list.Any(o =>
                                                o.aapiUrl.ToLower()
                                                == (newrouteurl + "CheckAudit").ToLower()
                                            )
                                        )
                                        {
                                            functionMenu.iscomfirm = true;
                                        }
                                        if (
                                            list.Any(o =>
                                                o.aapiUrl.ToLower()
                                                == (newrouteurl + "CheckRoleResource").ToLower()
                                            )
                                        )
                                        {
                                            functionMenu.isroleresource = true;
                                        }
                                        if (
                                            list.Any(o =>
                                                o.aapiUrl.ToLower()
                                                == (newrouteurl + "CheckCompany").ToLower()
                                            )
                                        )
                                        {
                                            functionMenu.iscompany = true;
                                        }
                                        if (
                                            list.Any(o =>
                                                o.aapiUrl.ToLower()
                                                == (newrouteurl + "CheckDepartment").ToLower()
                                            )
                                        )
                                        {
                                            functionMenu.isdepartment = true;
                                        }
                                        if (
                                            list.Any(o =>
                                                o.aapiUrl.ToLower()
                                                == (newrouteurl + "CheckSchool").ToLower()
                                            )
                                        )
                                        {
                                            functionMenu.isschool = true;
                                        }
                                        if (
                                            list.Any(o =>
                                                o.aapiUrl.ToLower()
                                                == (newrouteurl + "CheckRecyclebin").ToLower()
                                            )
                                        )
                                        {
                                            functionMenu.isrecyclebin = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        functionMenu.isadd = true;
                        functionMenu.isdelete = true;
                        functionMenu.isupdate = true;
                        functionMenu.isquery = true;
                        functionMenu.isimport = true;
                        functionMenu.isexport = true;
                        functionMenu.isdown = true;
                        functionMenu.isupload = true;
                        functionMenu.iscomfirm = true;
                        functionMenu.isroleresource = true;
                        functionMenu.iscompany = true;
                        functionMenu.isdepartment = true;
                        functionMenu.isschool = true;
                        functionMenu.isrecyclebin = true;
                    }
                }
                result.data = functionMenu;
                return result;
            });
        }

        /// <summary>
        /// 获取用户列表信息
        /// </summary>
        /// <returns></returns>
        public async Task<CommonResult> GetList(User query)
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var userTable = TableAtributeUtil.GetTable<User>();
                var role = TableAtributeUtil.GetTable<Role>();
                var userrole = TableAtributeUtil.GetTable<UserRole>();
                var LoginAppid = HttpContextExtendBase.GetLoginAppid();
                query.loginUserCode = HttpContextExtendBase.GetLoginCode();
                var LoginrName = HttpContextExtendBase.GetLoginrName();
                var tableName =
                    $"(select a.*,r.rids as rId from {userTable} a left join {userrole} r on r.uId=a.Id and r.type=1 )as urp";

                string sql = query.GetQueryString<User>(
                    (a) =>
                    {
                        string rId = string.Empty;
                        if (!string.IsNullOrEmpty(query.rName))
                        {
                            var rolesql =
                                $"select Id from {role} where rName like '%{query.rName}%';";
                            var rolelist = baseApplication.mySqlSugar.Query<Role>(
                                rolesql,
                                null,
                                out var msg
                            );
                            if (string.IsNullOrEmpty(msg) && rolelist != null && rolelist.Count > 0)
                            {
                                rId = String.Join(
                                    ",",
                                    rolelist.Select(o => o.Id.ToString()).Distinct().ToList()
                                );
                            }
                            else
                            {
                                rId = "0";
                            }
                        }
                        if (!string.IsNullOrEmpty(rId))
                        {
                            a += $" and  (FIND_IN_SET('{rId}',rId) or FIND_IN_SET(rId,'{rId}')) ";
                        }

                        if (
                            string.Compare(query.loginUserCode, "ajng", true) != 0
                            && string.Compare(LoginAppid, "admin", true) != 0
                        )
                        {
                            var LoginuId = HttpContextExtendBase.GetLoginuId();
                            var sql =
                                $"select Id,associateuon,associateuonuser from {userTable} where Id='{LoginuId}' and status = 1 and associateuon = '是';";
                            var userlist = baseApplication.mySqlSugar.Query<User>(sql, out var msg);
                            if (string.IsNullOrEmpty(msg) && userlist != null && userlist.Count > 0)
                            {
                                var associateuonuser = userlist.FirstOrDefault().associateuonuser;
                                if (!string.IsNullOrEmpty(associateuonuser))
                                {
                                    a +=
                                        $" and  (FIND_IN_SET(uCode,'{associateuonuser}') or  uCode='{query.loginUserCode}')) ";
                                }
                                else
                                {
                                    a += $" and  (uCode='{query.loginUserCode}') ";
                                }
                            }
                            else
                            {
                                a += $" and  (uCode='{query.loginUserCode}' ) ";
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(query.uCode))
                            {
                                a += string.Format(" and uCode like '%{0}%' ", query.uCode);
                            }
                        }
                        if (!string.IsNullOrEmpty(query.Idb))
                        {
                            a += string.Format(" and Id like '%{0}%' ", query.Idb);
                        }

                        if (!string.IsNullOrEmpty(query.LoginType))
                        {
                            a += $" and LoginType='{query.LoginType}' ";
                        }
                        if (!string.IsNullOrEmpty(query.sttime))
                        {
                            a += $" and logintime>='{query.sttime}' ";
                        }
                        if (!string.IsNullOrEmpty(query.ettime))
                        {
                            a += $" and logintime<='{query.ettime}' ";
                        }
                        return a;
                    }
                );
                if (string.Compare(query.loginUserCode, "ajng", true) != 0)
                {
                    sql += " and uCode<>'ajng' ";
                }
                UserQuery userQuery = new UserQuery()
                {
                    tableName = tableName,
                    sqlWhere = sql,
                    sortFile = query.sortFile,
                    sortType = query.sortType,
                    pageIndex = query.pageIndex,
                    pageSize = query.pageSize,
                    files = "*"
                };
                result = baseApplication
                    .GetList<User>(
                        userQuery,
                        false,
                        (list, total) =>
                        {
                            if (list != null && list.Count > 0)
                            {
                                var rolelist = UserAuthorCache.GetRolecache();
                                var userrolelist = UserAuthorCache.GetUserRolecache();
                                var diclist = UserAuthorCache.GetDictionariescache();
                                list.ForEach(o =>
                                {
                                    //var jmpwd = EnDecryptionUtil.AesDecrypt(o.uPwd);
                                    //o.uPwd = EnDecryptionUtil.DESEncryptionb(jmpwd);
                                    if (rolelist != null && rolelist.Count > 0)
                                    {
                                        if (userrolelist != null && userrolelist.Count > 0)
                                        {
                                            var haveuserrole = userrolelist.Where(b =>
                                                b.uId == o.Id && b.type == 1
                                            );
                                            if (haveuserrole != null && haveuserrole.Count() > 0)
                                            {
                                                var rIds = haveuserrole
                                                    .FirstOrDefault()
                                                    .rids.Split(',');
                                                var haverole = rolelist.Where(o =>
                                                    rIds.Any(b => b == o.Id.ToString())
                                                );
                                                if (haverole != null && haverole.Count() > 0)
                                                {
                                                    o.rName = String.Join(
                                                        ",",
                                                        haverole.Select(o => o.rName)
                                                    );
                                                }
                                            }
                                        }
                                    }
                                    if (diclist != null && diclist.Count > 0)
                                    {
                                        if (!string.IsNullOrEmpty(o.pca))
                                        {
                                            List<string> dicaname = new List<string>();
                                            foreach (var itemb in o.pca.Split(','))
                                            {
                                                var dica = diclist.Where(o =>
                                                    o.Id == itemb.GetIntValue()
                                                );
                                                if (dica.Count() > 0)
                                                {
                                                    dicaname.Add(dica.FirstOrDefault().dName);
                                                }
                                            }
                                            if (dicaname.Count > 0)
                                            {
                                                o.pcaremark = String.Join("", dicaname);
                                            }
                                        }
                                    }
                                });
                            }
                        }
                    )
                    .GetAwaiter()
                    .GetResult();
                var newdata = new
                {
                    list = result.data,
                    pageSize = query.pageSize,
                    pageNum = query.pageIndex,
                    total = result.count
                };
                result.data = newdata;
                return result;
            });
        }

        /// <summary>
        /// 获取用户下属信息列表
        /// </summary>
        /// <param name="uId"></param>
        /// <param name="ucode"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<CommonResult> GetListb(
            string uId,
            string ucode,
            int pageIndex,
            int pageSize
        )
        {
            return await baseApplication.DoAction(
                BusinessType.user,
                BusinessActionType.update,
                BusinessLogType.NoWrite,
                HttpContextExtendBase.GetLoginCode(),
                uId,
                "获取用户绑定下属信息",
                (baseService) =>
                {
                    string msg = string.Empty;
                    CommonResult result = new CommonResult();
                    var tableName = TableAtributeUtil.GetTable<User>();
                    var userrole = TableAtributeUtil.GetTable<UserRole>();
                    var LoginCode = HttpContextExtendBase.GetLoginCode();
                    var LoginAppid = HttpContextExtendBase.GetLoginAppid();
                    List<User> userlist = new List<User>();
                    if (
                        string.Compare(LoginCode, "ajng", true) != 0
                        && string.Compare(LoginAppid, "admin", true) != 0
                    )
                    {
                        var usrroleall = baseApplication.mySqlSugar.QueryByExpression<UserRole>(
                            o => o.status == 1,
                            out msg
                        );
                        var userroledata = usrroleall.Where(o => o.uId == uId.GetIntValue());
                        if (
                            string.IsNullOrEmpty(msg)
                            && userroledata != null
                            && userroledata.Count() > 0
                        )
                        {
                            var rids = userroledata.FirstOrDefault().rids;
                            List<long> uids = new List<long>();
                            foreach (var rid in rids.Split(','))
                            {
                                var data = usrroleall.Where(o =>
                                    o.rids.Split(',').Any(c => c == rid)
                                );
                                foreach (var item in data)
                                {
                                    uids.Add(item.uId);
                                }
                            }
                            userlist = UserAuthorCache
                                .GetUsercache()
                                .Where(o => uids.Any(b => b == o.Id))
                                .ToList();
                            if (string.IsNullOrEmpty(msg) && userlist != null && userlist.Count > 0)
                            {
                                var data = UserAuthorCache
                                    .GetUsercache()
                                    .Where(o => o.Id == uId.GetLongValue())
                                    .ToList();
                                var Index = 1;
                                foreach (User item in data)
                                {
                                    if (!string.IsNullOrEmpty(item.associateuonuser))
                                    {
                                        var associateuonuser = item.associateuonuser.Split(',');
                                        foreach (var user in userlist)
                                        {
                                            if (associateuonuser.Any(o => o == user.uCode))
                                            {
                                                user.ischecked = true;
                                                user.parentName = item.uName;
                                                user.checkedindex = Index;
                                                Index++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        userlist = UserAuthorCache
                            .GetUsercache()
                            .Where(o => o.uCode != "ajng")
                            .ToList();
                        if (string.IsNullOrEmpty(msg) && userlist != null && userlist.Count > 0)
                        {
                            var data = UserAuthorCache
                                .GetUsercache()
                                .Where(o => o.Id == uId.GetLongValue())
                                .ToList();
                            var Index = 1;
                            foreach (User item in data)
                            {
                                if (!string.IsNullOrEmpty(item.associateuonuser))
                                {
                                    var associateuonuser = item.associateuonuser.Split(',');
                                    foreach (var user in userlist)
                                    {
                                        if (associateuonuser.Any(o => o == user.uCode))
                                        {
                                            user.ischecked = true;
                                            user.parentName = item.uName;
                                            user.checkedindex = Index;
                                            Index++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(ucode))
                    {
                        userlist = userlist.Where(o => o.uCode.Contains(ucode)).ToList();
                    }
                    result.count = userlist.Count;
                    result.data = userlist
                        .OrderBy(o => o.checkedindex)
                        .Skip((pageIndex - 1) * pageSize)
                        .Take(pageSize);
                    return result;
                }
            );
        }

        /// <summary>
        /// 获取用户角色列表
        /// </summary>
        /// <param name="uCode"></param>
        /// <param name="rName"></param>
        /// <param name="type"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<CommonResult> GetListg(
            string uCode,
            string rName,
            int type,
            int pageIndex,
            int pageSize
        )
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var msg = string.Empty;
                var sql = $"where 1=1  and status<>-9  and statusb<>-9 and type={type} ";
                var loginUserCode = HttpContextExtendBase.GetLoginCode();
                if (string.Compare(loginUserCode, "ajng", true) != 0)
                {
                    sql += " and uCode<>'ajng' ";
                }
                var userTable = TableAtributeUtil.GetTable<User>();
                var role = TableAtributeUtil.GetTable<Role>();
                var userrole = TableAtributeUtil.GetTable<UserRole>();
                var tableName = string.Empty;
                if (type == 1)
                {
                    tableName =
                        $"(select b.type, b.cTime,c.status as statusb,GROUP_CONCAT(DISTINCT(c.rName)) as rName,GROUP_CONCAT(DISTINCT(c.Id)) as rId,b.Id,a.status,a.uCode from {userTable} a inner join {userrole} b on a.Id=b.uId inner join {role} c on FIND_IN_SET(c.Id,b.rids)  group by uCode,Id,status,statusb,b.cTime,c.Id) as urp";
                }

                if (!string.IsNullOrEmpty(uCode))
                {
                    sql += $" and uCode like '%{uCode}%' ";
                }
                if (!string.IsNullOrEmpty(rName))
                {
                    sql += $" and rName like '%{rName}%' ";
                }
                UserQuery userQuery = new UserQuery()
                {
                    tableName = tableName,
                    sqlWhere = sql,
                    sortFile = "Id",
                    sortType = "desc",
                    pageIndex = pageIndex,
                    pageSize = pageSize,
                    files = "*"
                };
                long total = 0;
                List<User> userlist = new List<User>();
                baseApplication.mySqlSugar.GetList<User>(
                    userQuery,
                    out msg,
                    out userlist,
                    out total
                );
                result.msg = msg;
                result.count = total;
                result.data = userlist;

                var newresult = new
                {
                    msg = result.msg,
                    code = result.code,
                    data = new { list = result.data, total = result.count }
                };
                result.data = newresult;
                return result;
            });
        }

        /// <summary>
        /// 获取角色资源列表
        /// </summary>
        /// <param name="rName"></param>
        /// <param name="resName"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<CommonResult> GetListd(
            string rName,
            string resName,
            int pageIndex,
            int pageSize
        )
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var msg = string.Empty;
                var sql = "where 1=1  and status<>-9 and eId<>'' and statusb<>-9 ";
                var loginUserCode = HttpContextExtendBase.GetLoginCode();
                if (string.Compare(loginUserCode, "ajng", true) != 0)
                {
                    sql += " and Id<>1 ";
                }
                var role = TableAtributeUtil.GetTable<Role>();
                var roleres = TableAtributeUtil.GetTable<RoleResource>();
                var author = TableAtributeUtil.GetTable<Menu>();
                var tableName =
                    $"(select e.Id as aId,b.cTime,a.status,b.Id,a.rName,e.status as statusb,GROUP_CONCAT(DISTINCT(e.Id)) as eId,GROUP_CONCAT(DISTINCT(e.aName)) as resName from {role} a left join {roleres} b on a.Id=b.rId left join {author} e on FIND_IN_SET(e.Id,b.aIds) group by rName,Id,status,statusb, b.cTime,e.Id) as urp";
                if (!string.IsNullOrEmpty(rName))
                {
                    sql += $" and rName like '%{rName}%' ";
                }
                if (!string.IsNullOrEmpty(resName))
                {
                    sql += $" and resName like '%{resName}%' ";
                }
                RoleQuery userQuery = new RoleQuery()
                {
                    tableName = tableName,
                    sqlWhere = sql,
                    sortFile = "Id",
                    sortType = "desc",
                    pageIndex = pageIndex,
                    pageSize = pageSize,
                    files = "*"
                };
                long total = 0;
                List<Role> rolelist = new List<Role>();
                baseApplication.mySqlSugar.GetList<Role>(
                    userQuery,
                    out msg,
                    out rolelist,
                    out total
                );
                result.msg = msg;
                result.count = total;
                result.data = rolelist;

                var newresult = new
                {
                    msg = result.msg,
                    code = result.code,
                    data = new { list = result.data, total = result.count }
                };
                result.data = newresult;
                return result;
            });
        }

        /// <summary>
        /// 获取用户角色资源列表
        /// </summary>
        /// <param name="uCode"></param>
        /// <param name="rName"></param>
        /// <param name="resName"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<CommonResult> GetListc(
            string uCode,
            string rName,
            string resName,
            int pageIndex,
            int pageSize
        )
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var msg = string.Empty;
                var usercachelist = UserAuthorCache.GetUsercache();
                var rolecachelist = UserAuthorCache.GetRolecache();
                var sql = "where 1=1  and u.status<>-9 and aids<>'' ";
                var loginUserCode = HttpContextExtendBase.GetLoginCode();
                if (string.Compare(loginUserCode, "ajng", true) != 0)
                {
                    sql += " and uId<>1 ";
                }
                var table = TableAtributeUtil.GetTable<URPermission>();
                var author = TableAtributeUtil.GetTable<Menu>();
                if (!string.IsNullOrEmpty(uCode))
                {
                    var userdatalist = usercachelist.Where(o => o.uCode.Contains(uCode));
                    if (userdatalist.Count() > 0)
                    {
                        var uIds = String.Join(",", userdatalist.Select(o => o.Id));
                        sql += $" and uId in({uIds})";
                    }
                    else
                    {
                        sql += $" and uId=-1 ";
                    }
                }
                if (!string.IsNullOrEmpty(rName))
                {
                    var roledatalist = rolecachelist.Where(o => o.rName.Contains(rName));
                    if (roledatalist.Count() > 0)
                    {
                        var rIds = String.Join(",", roledatalist.Select(o => o.Id));
                        sql += $" and rId in({rIds})";
                    }
                    else
                    {
                        sql += $" and rId=-1 ";
                    }
                }
                if (!string.IsNullOrEmpty(resName))
                {
                    sql += $" and a.aName like '%{resName}%' ";
                }
                var tableName =
                    $"(select a.Id as aId,u.status,u.Id,u.uId,u.rId,a.aName as resName from {table} u left join {author} a on FIND_IN_SET(a.Id,u.aIds) {sql} group by a.Id,u.Id) as urp ";
                UserQuery userQuery = new UserQuery()
                {
                    tableName = tableName,
                    sqlWhere = string.Empty,
                    sortFile = "Id",
                    sortType = "desc",
                    pageIndex = pageIndex,
                    pageSize = pageSize,
                    files = "*"
                };
                long total = 0;
                List<URPermission> list = new List<URPermission>();
                baseApplication.mySqlSugar.GetList<URPermission>(
                    userQuery,
                    out msg,
                    out list,
                    out total
                );
                if (list.Count > 0)
                {
                    list.ForEach(item =>
                    {
                        var userdata = usercachelist.Where(o => o.Id == item.uId);
                        if (userdata.Count() > 0)
                        {
                            item.uCode = userdata.FirstOrDefault().uCode;
                        }
                        var roledata = rolecachelist.Where(o => o.Id == item.rId);
                        if (roledata.Count() > 0)
                        {
                            item.rName = roledata.FirstOrDefault().rName;
                        }
                    });
                }
                result.msg = msg;
                result.count = total;
                result.data = list;
                return result;
            });
        }

        /// <summary>
        /// 获取用户详细信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<CommonResult> GetDetail(int Id)
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var list = baseApplication.mySqlSugar.QueryByExpression<User>(
                    o => o.Id == Id,
                    out var msg
                );
                if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
                {
                    var user = list.FirstOrDefault();
                    var rolelist = UserAuthorCache.GetRolecache();
                    var userrolelist = UserAuthorCache.GetUserRolecache();
                    if (rolelist != null && rolelist.Count > 0)
                    {
                        if (userrolelist != null && userrolelist.Count > 0)
                        {
                            var haveuserrole = userrolelist.Where(b =>
                                b.uId == user.Id && b.type == 1
                            );
                            if (haveuserrole != null && haveuserrole.Count() > 0)
                            {
                                var rIds = haveuserrole.FirstOrDefault().rids.Split(',');
                                var haverole = rolelist.Where(o =>
                                    rIds.Any(b => b == o.Id.ToString())
                                );
                                if (haverole != null && haverole.Count() > 0)
                                {
                                    user.rName = String.Join(",", haverole.Select(o => o.rName));
                                    user.rId = String.Join(",", haverole.Select(o => o.Id));
                                }
                            }
                        }
                    }
                    var uPwd = AesEncryptionUtil.Decrypt(user.uPwd);
                    user.uPwd = EnDecryptionUtil.DESEncryptionb(uPwd);
                    result.data = user;
                }
                result.msg = msg;
                return result;
            });
        }

        /// <summary>
        /// 解除用户绑定相关信息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<CommonResult> Unbinduserrole(Unbinddata data)
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var LoginCode = HttpContextExtendBase.GetLoginCode();
                if (string.Compare(LoginCode, "ajng", true) != 0)
                {
                    result.msg = ImplementResult.Nopermissiontooperate.GetRemark();
                    return result;
                }
                string sql = string.Empty;
                string msg = string.Empty;
                List<Unbinddata> list = new List<Unbinddata>();
                if (string.IsNullOrEmpty(data.data))
                {
                    result.msg = ImplementResult.ParameterException.GetRemark();
                    return result;
                }
                else
                {
                    list = JsonUtil.UnRendResults<Unbinddata>(data.data);
                    if (list.Count == 0)
                    {
                        result.msg = ImplementResult.ParameterException.GetRemark();
                        return result;
                    }
                }
                StringBuilder stringBuilder = new StringBuilder();
                foreach (var data in list)
                {
                    if (data.type == 1) //用户角色解绑
                    {
                        var userrole = TableAtributeUtil.GetTable<UserRole>();
                        sql = $"select * from {userrole} where Id={data.Id};";
                        var userrolelist = baseApplication.mySqlSugar.Query<UserRole>(
                            sql,
                            null,
                            out msg
                        );
                        if (
                            string.IsNullOrEmpty(msg)
                            && userrolelist != null
                            && userrolelist.Count > 0
                        )
                        {
                            var rids = userrolelist.FirstOrDefault().rids.Split(",");
                            List<string> ridlist = new List<string>();
                            foreach (var item in rids)
                            {
                                if (item.GetLongValue() != data.rId)
                                {
                                    ridlist.Add(item);
                                }
                            }
                            if (ridlist.Count == 0)
                            {
                                sql = $"delete from {userrole} where Id={data.Id};";
                            }
                            else
                            {
                                sql =
                                    $"update {userrole} set rids='{String.Join(",", ridlist)}' where Id={data.Id};";
                            }
                        }
                    }
                    if (data.type == 2) //角色资源解绑
                    {
                        var roleresource = TableAtributeUtil.GetTable<RoleResource>();
                        sql = $"select * from {roleresource} where Id={data.Id};";
                        var userrolelist = baseApplication.mySqlSugar.Query<RoleResource>(
                            sql,
                            null,
                            out msg
                        );
                        if (
                            string.IsNullOrEmpty(msg)
                            && userrolelist != null
                            && userrolelist.Count > 0
                        )
                        {
                            var aids = userrolelist.FirstOrDefault().aIds.Split(",");
                            List<string> aidlist = new List<string>();
                            foreach (var item in aids)
                            {
                                if (item.GetLongValue() != data.aId)
                                {
                                    aidlist.Add(item);
                                }
                            }
                            if (aidlist.Count == 0)
                            {
                                sql = $"delete from {roleresource} where Id={data.Id};";
                            }
                            else
                            {
                                sql =
                                    $"update {roleresource} set aIds='{String.Join(",", aidlist)}' where Id={data.Id};";
                            }
                        }
                    }
                    if (data.type == 3) //用户角色资源解绑
                    {
                        var urmtable = TableAtributeUtil.GetTable<URPermission>();
                        sql = $"select * from {urmtable} where Id={data.Id};";
                        var urmlist = baseApplication.mySqlSugar.Query<URPermission>(
                            sql,
                            null,
                            out msg
                        );
                        if (string.IsNullOrEmpty(msg) && urmlist != null && urmlist.Count > 0)
                        {
                            var aIds = urmlist.FirstOrDefault().aIds.Split(",");
                            List<string> aidlist = new List<string>();
                            foreach (var item in aIds)
                            {
                                if (item.GetLongValue() != data.aId)
                                {
                                    aidlist.Add(item);
                                }
                            }
                            if (aidlist.Count == 0)
                            {
                                sql = $"delete from {urmtable} where Id={data.Id};";
                            }
                            else
                            {
                                sql =
                                    $"update {urmtable} set aIds='{String.Join(",", aidlist)}' where Id={data.Id};";
                            }
                        }
                    }

                    baseApplication.mySqlSugar.ExecuteSql(sql, null, out msg);
                    stringBuilder.Append(msg);
                    if (data.type == 1)
                    {
                        UserAuthorCache.AddUserRolecache(baseApplication.mySqlSugar, true, true);
                    }
                    if (data.type == 2)
                    {
                        UserAuthorCache.AddRoleRescache(baseApplication.mySqlSugar, true, true);
                    }
                    if (data.type == 3)
                    {
                        UserAuthorCache.AddURMcache(baseApplication.mySqlSugar, true, true);
                    }
                }
                result.msg = stringBuilder.ToString();
                return result;
            });
        }

        /// <summary>
        /// 获取用户登录信息
        /// </summary>
        /// <param name="loginToken"></param>
        /// <returns></returns>
        public async Task<CommonResult> GetUserLoginInfo(SigninInfoQuery query)
        {
            CommonResult result = new CommonResult();
            var tableName = TableAtributeUtil.GetTable<SigninInfo>();
            string sql = string.Format(" where 1=1 ");
            string msg = string.Empty;
            var loginUserCode = HttpContextExtendBase.GetLoginCode();
            if (
                string.Compare(loginUserCode, "ajng", true) != 0
                && string.Compare(loginUserCode, "sysadmin", true) != 0
                && string.Compare(loginUserCode, "jtfz", true) != 0
            )
            {
                sql += string.Format(" and logincode='{0}' ", loginUserCode);
            }
            else
            {
                if (!string.IsNullOrEmpty(query.logincode))
                {
                    sql += string.Format(" and logincode like '%{0}%' ", loginUserCode);
                }
            }
            if (!string.IsNullOrEmpty(query.ipaddress))
            {
                sql += string.Format(" and ipaddress like '%{0}%' ", query.ipaddress);
            }
            if (!string.IsNullOrEmpty(query.ipv4address))
            {
                sql += string.Format(" and ipv4address like '%{0}%' ", query.ipv4address);
            }
            if (!string.IsNullOrEmpty(query.lmacaddress))
            {
                sql += string.Format(" and lmacaddress like '%{0}%' ", query.lmacaddress);
            }
            if (!string.IsNullOrEmpty(query.osystem))
            {
                sql += string.Format(" and osystem like '%{0}%' ", query.osystem);
            }
            if (!string.IsNullOrEmpty(query.osystemtype))
            {
                sql += string.Format(" and osystemtype like '%{0}%' ", query.osystemtype);
            }
            if (!string.IsNullOrEmpty(query.loginouttime))
            {
                var start = query.loginouttime.Split(',')[0];
                var end = query.loginouttime.Split(',')[1];
                sql += string.Format(
                    " and loginouttime >='{0}' and loginouttime<='{1}' ",
                    start,
                    end
                );
            }
            if (!string.IsNullOrEmpty(query.logintime))
            {
                var start = query.logintime.Split(',')[0];
                var end = query.logintime.Split(',')[1];
                sql += string.Format(" and logintime >='{0}' and logintime<='{1}' ", start, end);
            }
            if (string.IsNullOrEmpty(query.sortType))
            {
                query.sortType = "desc";
            }

            if (string.IsNullOrEmpty(query.sortFile))
            {
                query.sortFile = "Id";
            }
            List<SigninInfo> SigninInfo = new List<SigninInfo>();
            SigninInfoQuery signigQuery = new SigninInfoQuery()
            {
                tableName = tableName,
                sqlWhere = sql,
                sortFile = query.sortFile,
                sortType = query.sortType,
                pageIndex = query.pageIndex,
                pageSize = query.pageSize,
                files = "*"
            };
            return await baseApplication.GetList<SigninInfo>(signigQuery);
        }

        /// <summary>
        /// 获取用户角色资源列表信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<CommonResult> GetUserRoleResList(string Id)
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var user = TableAtributeUtil.GetTable<User>();
                var role = TableAtributeUtil.GetTable<Role>();
                var author = TableAtributeUtil.GetTable<Menu>();
                var ura = TableAtributeUtil.GetTable<URPermission>();
                var urr = TableAtributeUtil.GetTable<UserRole>();
                string msg = string.Empty;
                var sqla =
                    $"select a.rName,a.Id from {role} a left join {urr} b on FIND_IN_SET(a.Id,b.rids)where b.uId = {Id}; ";
                var roles = baseApplication.mySqlSugar.Query<Role>(sqla, out msg);
                string rname = string.Empty;
                List<string> aulist = new List<string>();
                if (string.IsNullOrEmpty(msg) && roles.Count > 0)
                {
                    rname = string.Join(",", roles.Select(o => o.rName));
                    foreach (var item in roles)
                    {
                        var sqlb =
                            $"select a.aName from {author} a left join {ura} b on FIND_IN_SET(a.Id,b.aIds) where b.uId='{Id}' and a.aType<>3 and rId='{item.Id}';";
                        var authors = baseApplication.mySqlSugar.Query<Menu>(sqlb, out msg);
                        if (string.IsNullOrEmpty(msg) && authors.Count > 0)
                        {
                            foreach (var itemb in authors)
                            {
                                if (!aulist.Any(o => o == itemb.aName))
                                {
                                    aulist.Add(itemb.aName);
                                }
                            }
                        }
                    }
                    result.count = 1;
                    result.data = new { rname, aulist };
                }
                else
                {
                    result.count = 0;
                    result.msg = msg;
                }
                ;
                return result;
            });
        }

        /// <summary>
        ///  检查用户是否首次登录，是则需要修改密码
        /// </summary>
        /// <returns></returns>
        public async Task<CommonResult> GetLoginFirst()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var user = TableAtributeUtil.GetTable<User>();
                var LoginuId = HttpContextExtendBase.GetLoginuId();
                var sql =
                    $"select lasttimeupw,resetpwd from {user} where Id='{LoginuId}' and status<>-9;";
                var userdata = baseApplication.mySqlSugar.Query<User>(sql, out var msg);
                result.msg = msg;
                if (string.IsNullOrEmpty(msg) && userdata != null && userdata.Count > 0)
                {
                    var lasttimeupw = userdata.FirstOrDefault().lasttimeupw;
                    var resetpwd = userdata.FirstOrDefault().resetpwd;
                    if (string.IsNullOrEmpty(lasttimeupw))
                    {
                        result.data = "0001-01-01 00:00:00";
                    }
                    if (string.Compare(resetpwd, "是", true) == 0)
                    {
                        result.data = "重置密码";
                    }
                }
                return result;
            });
        }

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="loginUserCode"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<CommonResult> Delete(string Id, string loginUserCode, string type)
        {
            return await baseApplication.Delete<User>(
                Id,
                loginUserCode,
                type,
                BusinessType.user,
                (autofaceInstance, mySqlSugar, newId) =>
                {
                    CommonResult result = new CommonResult();
                    loginUserCode = HttpContextExtendBase.GetLoginCode();
                    string msg = string.Empty;
                    //if (string.Compare(loginUserCode, "ajng", true) != 0)
                    //{
                    //  result.code = (int)CodeResult.nolegitimate;
                    //  result.msg = ImplementResult.Nopermissiontooperate.GetRemark();
                    //  result.data = null;
                    //  result.count = 0;
                    //  return result;
                    //}
                    User info = new User();
                    foreach (var item in Id.Split(','))
                    {
                        baseApplication.mySqlSugar.QueryInfoByID(
                            item.GetIntValue(),
                            out msg,
                            out info
                        );
                        autofaceInstance.DoWork(
                            BusinessType.user,
                            BusinessActionType.delete,
                            "删除用户",
                            type + "Delete[" + info.uCode + "]用户信息",
                            BusinessLogType.writeLogToDataBase,
                            (o) =>
                            {
                                if (info == null)
                                {
                                    result.code = (int)CodeResult.fail;
                                    result.msg = ImplementResult.WorkErr.GetRemark();
                                    result.data = null;
                                    result.count = 0;
                                    return result;
                                }

                                if (info.Id > 0)
                                {
                                    if (string.Compare(info.uCode, "ajng", true) == 0)
                                    {
                                        result.code = (int)CodeResult.fail;
                                        result.msg = "系统数据不能删除!";
                                        result.data = null;
                                        result.count = 0;
                                        return result;
                                    }
                                    var tableName = TableAtributeUtil.GetTable<User>();
                                    string sql = string.Empty;
                                    if (type == "-9")
                                    {
                                        sql =
                                            $"update {tableName} set status=-9 where Id='{info.Id}';";
                                        baseApplication.mySqlSugar.ExecuteSql(sql, null, out msg);
                                        result.msg = msg;
                                    }
                                    else
                                    {
                                        tableName = TableAtributeUtil.GetTable<UserRole>();
                                        sql = string.Format(
                                            "select Id from {0} where uId='{1}'",
                                            tableName,
                                            item
                                        );
                                        var dt = baseApplication.mySqlSugar.GetDataTable(
                                            sql,
                                            null,
                                            out msg
                                        );
                                        if (dt.Rows.Count > 0)
                                        {
                                            if (string.Compare(loginUserCode, "ajng", true) == 0)
                                            {
                                                var urId = dt.Rows[0]["Id"]
                                                    .ToString()
                                                    .GetIntValue();
                                                sql =
                                                    $"delete from '{tableName}' where Id='{urId}';";
                                                baseApplication.mySqlSugar.ExecuteSql(
                                                    sql,
                                                    null,
                                                    out msg
                                                );
                                            }
                                            else
                                            {
                                                result.code = (int)CodeResult.fail;
                                                result.msg = "当前用户已经绑定角色信息，请先解除已它关联的角色信息!";
                                                result.data = null;
                                                result.count = 0;
                                                return result;
                                            }
                                        }

                                        tableName = TableAtributeUtil.GetTable<URPermission>();
                                        sql = string.Format(
                                            "select Id from {0} where uId='{1}'",
                                            tableName,
                                            item
                                        );
                                        dt = baseApplication.mySqlSugar.GetDataTable(
                                            sql,
                                            null,
                                            out msg
                                        );
                                        if (dt.Rows.Count > 0)
                                        {
                                            if (string.Compare(loginUserCode, "ajng", true) == 0)
                                            {
                                                var uruId = dt.Rows[0]["Id"]
                                                    .ToString()
                                                    .GetIntValue();
                                                sql =
                                                    $"delete from '{tableName}' where Id='{uruId}';";
                                                baseApplication.mySqlSugar.ExecuteSql(
                                                    sql,
                                                    null,
                                                    out msg
                                                );
                                            }
                                            else
                                            {
                                                result.code = (int)CodeResult.fail;
                                                result.msg = "当前用户已经绑定资源信息，请先解除已它关联的资源信息!";
                                                result.data = null;
                                                result.count = 0;
                                                return result;
                                            }
                                        }
                                        tableName = TableAtributeUtil.GetTable<User>();
                                        sql = $"delete from {tableName} where Id='{info.Id}';";
                                        baseApplication.mySqlSugar.ExecuteSql(sql, null, out msg);
                                        result.msg = msg;
                                    }
                                }
                                else
                                {
                                    result.msg = "[" + Id + "]用户信息不存在";
                                }
                                return result;
                            },
                            null,
                            ref result
                        );
                    }
                    UserAuthorCache.AddUsercache(baseApplication.mySqlSugar, true, true);
                    return result;
                }
            );
        }

        /// <summary>
        /// 还原用户信息
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="loginUserCode"></param>
        /// <returns></returns>
        public async Task<CommonResult> Reduction(string Id, string loginUserCode)
        {
            return await baseApplication.Reduction<User>(
                Id,
                loginUserCode,
                BusinessType.user,
                (a, b, info) =>
                {
                    return info.uName + "-" + info.uCode;
                },
                (db, data) =>
                {
                    UserAuthorCache.AddUsercache(baseApplication.mySqlSugar, true, true);
                }
            );
        }

        /// <summary>
        /// 判断服务器是否升级重启
        /// </summary>
        /// <returns></returns>
        public async Task<CommonResult> TheServerInit()
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult() { count = 0, data = null };
                return result;
            });
        }

        /// <summary>
        /// 修改用户登录密码
        /// </summary>
        /// <param name="uCode"></param>
        /// <param name="uId"></param>
        /// <param name="ypwd"></param>
        /// <param name="nywd"></param>
        /// <returns></returns>
        public async Task<CommonResult> UpdatePwd(UserPwd userPwd)
        {
            CommonResult result = new CommonResult();
            var LoginCode = HttpContextExtendBase.GetLoginCode();
            var LoginuId = HttpContextExtendBase.GetLoginuId();
            if (string.IsNullOrEmpty(LoginCode) || string.IsNullOrEmpty(LoginuId))
            {
                result.msg = ImplementResult.IDTokenEmpty.GetRemark();
                return result;
            }
            //userPwd.Id = LoginuId;
            return await baseApplication.DoAction(
                BusinessType.user,
                BusinessActionType.update,
                BusinessLogType.writeLogToDataBase,
                LoginCode,
                JsonUtil.ToJson(userPwd),
                "修改用户登录密码",
                (mySqlSugar) =>
                {
                    string msg = string.Empty;
                    string sql = string.Empty;
                    var usertable = TableAtributeUtil.GetTable<User>();
                    sql = $"select uPwd from {usertable} where Id={userPwd.Id};";
                    User useryz = new User();
                    baseApplication.mySqlSugar.QueryInfoByID<User>(
                        userPwd.Id.GetIntValue(),
                        out msg,
                        out useryz
                    );
                    var curpass = useryz.uPwd;
                    userPwd.oldPassword = EnDecryptionUtil.DESDecryptbyqd(userPwd.oldPassword);
                    //userPwd.oldPassword = EnDecryptionUtil.AesEncrypt(userPwd.oldPassword);
                    userPwd.oldPassword = AesEncryptionUtil.Encrypt(userPwd.oldPassword);
                    if (string.Compare(curpass, userPwd.oldPassword, true) != 0)
                    {
                        result.msg = "原密码错误!";
                        result.code = (int)ImplementResult.UpdatePwdErr;
                        return result;
                    }
                    else
                    {
                        var tableName = TableAtributeUtil.GetTable<User>();
                        userPwd.newPassword = EnDecryptionUtil.DESDecryptbyqd(userPwd.newPassword);
                        //userPwd.newPassword = EnDecryptionUtil.AesEncrypt(userPwd.newPassword);
                        userPwd.newPassword = AesEncryptionUtil.Encrypt(userPwd.newPassword);
                        if (string.Compare(curpass, userPwd.newPassword, true) == 0)
                        {
                            sql =
                                $"update {tableName} set lasttimeupw='{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}',resetpwd='否' where Id={userPwd.Id};";
                            baseApplication.mySqlSugar.ExecuteSql(sql, null, out msg);
                        }
                        else
                        {
                            List<User> user = new List<User>();
                            tableName = TableAtributeUtil.GetTable<User>();
                            sql = string.Format(
                                "select * from {0} where Id={1};",
                                tableName,
                                userPwd.Id
                            );
                            var dt = baseApplication.mySqlSugar.GetDataTable(sql, null, out msg);
                            if (string.IsNullOrEmpty(msg))
                            {
                                if (dt.Rows.Count > 0)
                                {
                                    sql = string.Format(
                                        "update {0} set uPwd='{2}',lasttimeupw='{3}',resetpwd='{4}' where Id={1};  ",
                                        tableName,
                                        userPwd.Id,
                                        userPwd.newPassword,
                                        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                        "否"
                                    );
                                    baseApplication.mySqlSugar.ExecuteSql(sql, null, out msg);
                                    if (string.IsNullOrEmpty(msg))
                                    {
                                        //LogUtil.GetInstance.WriteLogOld("修改登录密码", userPwd.uCode + $",旧密码【{userPwd.ypwd}】,新密码【{userPwd.nywd}】", true);
                                    }
                                }
                            }
                        }
                    }
                    result.msg = msg;
                    return result;
                }
            );
        }

        /// <summary>
        /// 新增修改用户信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<CommonResult> AddOrUpdate(User info)
        {
            return await baseApplication.AddOrUpdate<User>(
                info,
                BusinessType.user,
                BusinessLogType.writeLogToDataBase,
                (mySqlSugar) =>
                {
                    CommonResult result = new CommonResult();
                    if (info.Id == 0 || string.Compare(info.resetpwd, "是", true) == 0)
                    {
                        info.uPwd = EnDecryptionUtil.DESDecryptbyqd(info.uPwd);
                        info.uPwd = AesEncryptionUtil.Encrypt(info.uPwd);
                        info.retrycount = 0;
                    }
                    string msg = string.Empty;
                    var table = string.Empty;
                    var sql = string.Empty;

                    if (info.Id == 0)
                    {
                        info.createuser = HttpContextExtendBase.GetLoginCode();
                        info.Id = baseApplication.mySqlSugar.Insert(info, out msg);
                        var LoginCode = HttpContextExtendBase.GetLoginCode();
                        var LoginuId = HttpContextExtendBase.GetLoginuId();
                        if (string.Compare(LoginCode, "ajng", true) != 0)
                        {
                            table = TableAtributeUtil.GetTable<User>();
                            sql =
                                $"select * from {table} where Id='{LoginuId}' and associateuon ='是';";
                            var userlist = baseApplication.mySqlSugar.Query<User>(sql, out msg);
                            if (string.IsNullOrEmpty(msg) && userlist != null && userlist.Count > 0)
                            {
                                var userdata = userlist.FirstOrDefault();
                                var associateuonuser = userdata.associateuonuser;
                                if (!string.IsNullOrEmpty(associateuonuser))
                                {
                                    var newasu = associateuonuser + "," + info.uCode;
                                    var newuas = String.Join(",", newasu.Split(',').Distinct());
                                    sql =
                                        $"update {table} set associateuonuser='{newuas}' where Id={LoginuId};";
                                }
                                else
                                {
                                    sql =
                                        $"update {table} set associateuonuser='{info.uCode}' where Id={LoginuId};";
                                }

                                baseApplication.mySqlSugar.ExecuteSql(sql, null, out msg);
                            }
                        }
                        UserAuthorCache.AddUsercache(baseApplication.mySqlSugar, true, true);
                    }
                    else
                    {
                        info.uPwd = EnDecryptionUtil.DESDecryptbyqd(info.uPwd);
                        info.uPwd = AesEncryptionUtil.Encrypt(info.uPwd);
                        info.modifyuser = HttpContextExtendBase.GetLoginCode();
                        User olduser = new User();
                        baseApplication.mySqlSugar.QueryInfoByID(
                            info.Id.ToString().GetIntValue(),
                            out msg,
                            out olduser
                        );
                        if (string.Compare(info.uPwd, olduser.uPwd, true) != 0)
                        {
                            info.uPwd = info.uPwd;
                        }
                        if (info.status == 1)
                        {
                            info.retrycount = 0;
                            info.retrytime = string.Empty;
                        }
                        baseApplication.mySqlSugar.Update(info, out msg);
                    }
                    result.msg = msg;
                    table = TableAtributeUtil.GetTable<UserRole>();
                    sql = $"delete from {table} where uId={info.Id} and type=1;";
                    baseApplication.mySqlSugar.ExecuteSql(sql, null, out msg);
                    if (!string.IsNullOrEmpty(info.rId))
                    {
                        var rolelist = UserAuthorCache.GetRolecache();
                        var rids = info.rId.Split(',');
                        var haverolelist = rolelist.Where(o => rids.Any(b => b == o.Id.ToString()));
                        if (haverolelist != null && haverolelist.Count() > 0)
                        {
                            var rolename = string.Join(",", haverolelist.Select(o => o.rName));
                            if (rolename.Contains("批量审核"))
                            {
                                var roledata = rolelist.Where(o => o.rName == "审核");
                                if (roledata != null && roledata.Count() > 0)
                                {
                                    info.rId = info.rId + "," + roledata.FirstOrDefault().Id;
                                }
                            }
                        }

                        UserRole userRole = new UserRole()
                        {
                            uId = info.Id,
                            status = 1,
                            rids = info.rId,
                            type = 1
                        };
                        baseApplication.mySqlSugar.InserBackId<UserRole>(userRole, out msg);
                        UserAuthorCache.AddUserRolecache(baseApplication.mySqlSugar, true, true);
                    }
                    UserAuthorCache.AddUsercache(baseApplication.mySqlSugar, true, true);
                    return result;
                },
                null
            );
        }

        /// <summary>
        /// 保存用户下属信息
        /// </summary>
        /// <param name="uId"></param>
        /// <param name="uCodes"></param>
        /// <param name="loginUserCode"></param>
        /// <returns></returns>
        public async Task<CommonResult> SaveUserOrgb(
            string uId,
            string uCodes,
            string loginUserCode
        )
        {
            return await baseApplication.DoAction(
                BusinessType.user,
                BusinessActionType.update,
                BusinessLogType.writeLogToDataBase,
                loginUserCode,
                "用户编号：" + uId + "|下属用户：" + uCodes,
                "保存用户下属信息",
                (baseService) =>
                {
                    CommonResult result = new CommonResult();
                    string msg = string.Empty;
                    var tableName = TableAtributeUtil.GetTable<User>();
                    var sql = $"update {tableName} set associateuonuser='{uCodes}' where Id={uId};";
                    baseApplication.mySqlSugar.ExecuteSql(sql, null, out msg);
                    result.msg = msg;
                    UserAuthorCache.AddUsercache(baseService, true, true);
                    return result;
                }
            );
        }

        /// <summary>
        /// 检查用户账号是否存在
        /// </summary>
        /// <param name="uCode"></param>
        /// <param name="loginUserCode"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<CommonResult> CheckUserCode(
            string uCode,
            string loginUserCode,
            string Id = ""
        )
        {
            return await baseApplication.CheckDataExists<User>(
                BusinessType.user,
                BusinessLogType.writeLogToDataBase,
                o => o.uCode == uCode && o.status != -9,
                "检查用户账号是否存在",
                Id
            );
        }

        /// <summary>
        /// 检查用户手机号是否存在
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="loginUserCode"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<CommonResult> CheckUserMobile(
            string mobile,
            string loginUserCode,
            string Id = ""
        )
        {
            return await baseApplication.CheckDataExists<User>(
                BusinessType.user,
                BusinessLogType.writeLogToDataBase,
                o => o.uMobile == mobile && o.status != -9,
                "检查用户手机号是否存在",
                Id
            );
        }

        /// <summary>
        /// 获取省市区数据
        /// </summary>
        /// <param name="loginUserCode"></param>
        /// <returns></returns>
        public async Task<CommonResult> GetCityData(string loginUserCode)
        {
            return await Task.Factory.StartNew(() =>
            {
                var tableName = TableAtributeUtil.GetTable<City>();
                string sql = $"select * from {tableName};";
                CommonResult result = new CommonResult();
                List<City> list = baseApplication.mySqlSugar.Query<City>(sql, out var msg);
                result.data = list;
                result.msg = msg;
                return result;
            });
        }

        /// <summary>
        /// 生成用户信息
        /// </summary>
        /// <param name="saveUserRoles"></param>
        /// <returns></returns>
        public async Task<CommonResult> Generateuser(SaveUserRole saveUserRoles)
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult result = new CommonResult();
                var user = TableAtributeUtil.GetTable<User>();
                StringBuilder stringBuilder = new StringBuilder();
                foreach (var uId in saveUserRoles.uids.Split(','))
                {
                    if (string.IsNullOrEmpty(uId.Trim()))
                    {
                        continue;
                    }
                    var uCode = uId.Split('-')[0].ReplaceStrChar();
                    var uName = uId.Split("-")[1].ReplaceStrChar();
                    var loginType = uId.Split("-")[2].ReplaceStrChar();
                    var sql = $"select * from {user} a where a.uCode='{uCode}' and a.status<>-9 ; ";
                    var userdata = baseApplication.mySqlSugar.Query<User>(sql, out var msg);
                    if (string.IsNullOrEmpty(msg) && userdata != null && userdata.Count == 0)
                    {
                        User userinfo = new User()
                        {
                            uCode = uCode,
                            uName = uName,
                            LoginType = loginType,
                            status = 1,
                            cTime = DateTime.Now,
                            retrycount = 0,
                            appid = uName,
                            uIdCardType = "0",
                            uSex = "",
                            uPwd = EnDecryptionUtil.AesEncrypt("Gzxx@123")
                        };
                        baseApplication.mySqlSugar.Insert<User>(userinfo, out msg);
                        if (!string.IsNullOrEmpty(msg))
                        {
                            stringBuilder.Append(msg + "|" + sql);
                        }
                    }
                }
                if (!string.IsNullOrEmpty(stringBuilder.ToString()))
                {
                    result.msg = stringBuilder.ToString();
                }
                return result;
            });
        }

        /// <summary>
        /// 用户账号信息导入
        /// </summary>
        /// <returns></returns>
        public async Task<CommonResult> ImportExcel(
            IFormFileCollection files,
            string path,
            string loginUserCode
        )
        {
            return await Task.Factory.StartNew(() =>
            {
                CommonResult commonResult = new CommonResult();
                StringBuilder result = new StringBuilder();
                baseApplication.autofaceInstance.DoWork(
                    BusinessType.user,
                    BusinessActionType.import,
                    files[0].FileName,
                    "用户账号管理数据",
                    BusinessLogType.writeLogToDataBase,
                    (o) =>
                    {
                        commonResult = AddExcelToData(files, path);
                        return commonResult;
                    },
                    null,
                    ref commonResult
                );
                return commonResult;
            });
        }

        /// <summary>
        /// 从Excel中导入数据到数据库表
        /// </summary>
        private static CommonResult AddExcelToData(IFormFileCollection files, string path)
        {
            StringBuilder msgsb = new StringBuilder();
            CommonResult commonResult = new CommonResult();
            string msg = string.Empty;
            ImportCache.InitImportData(
                files,
                path,
                "用户账号导入数据",
                out msg,
                (list) =>
                {
                    Dictionary<int, List<int>> aclist = new Dictionary<int, List<int>>();
                    foreach (var dt in list)
                    {
                        var Index = 1;
                        var usertable = TableAtributeUtil.GetTable<User>();
                        var roletable = TableAtributeUtil.GetTable<Role>();
                        var userrole = TableAtributeUtil.GetTable<UserRole>();
                        var sql = string.Empty;
                        string msg = string.Empty;
                        var user = TableAtributeUtil.GetTable<User>();
                        foreach (DataRow data in dt.Rows)
                        {
                            if (Index < 3)
                            {
                                Index++;
                                continue;
                            }
                            else
                            {
                                Index++;
                            }
                            var uCode = data.ItemArray[0].ToString(); //登录账号
                            if (string.IsNullOrEmpty(uCode))
                            {
                                break;
                            }
                        }
                    }
                    msg = msgsb.ToString();
                    if (!string.IsNullOrEmpty(msg))
                    {
                        commonResult.data = "导入校验出错";
                        commonResult.msg = msg;
                        return false;
                    }
                    else
                    {
                        commonResult.data = "导入完成";
                        return true;
                    }
                }
            );
            return commonResult;
        }
    }
}
